import jwt from 'jsonwebtoken';
import { Request, Response } from 'express';

const cookieKey = 'token';
const secrect = 'xinyue.yu';
//颁发jwt
function publish(res: Response, maxAge = 3600 * 24, info = {}) {
  const token = jwt.sign(info, secrect, {
    expiresIn: maxAge * 1000
  });
  //添加到cookie
  res.cookie(cookieKey, token, {
    maxAge,
    path: '/'
  });
  //添加其它
  res.header('authorization', token)
  return token;
}
function verify(req: Request) {
  let token

  token = req.headers.authorization
  if (!token) return null //没有token
  //authorization:Bearer token
  token = token.split(" ");
  token = token?.length === 1 ? token[0] : token[1];

  try {
    const result = jwt.verify(token, secrect);
    return result;
  } catch {
    return null;
  }
}
export default { publish, verify }
